package com.Limiter;

import lombok.extern.slf4j.Slf4j;

import java.util.Random;

/**
 * @Package: com.Limiter
 * @ClassName: LeakyBucketRateLimiter
 * @Author: h2cloud
 * @CreateTime: 2024/3/16 11:33 下午
 * @Description:
 */
@Slf4j
public class LeakyBucketRateLimiter implements Limiter {
	private final long capacity; // 桶的容量
	private final long rate; // 漏水速率（每秒允许的最大请求数）
	private long water; // 当前桶中的水量
	private long lastLeakTime; // 上一次漏水的时间

	public LeakyBucketRateLimiter(long capacity, long rate) {
		this.capacity = capacity;
		this.rate = rate;
		water = 0;
		lastLeakTime = System.currentTimeMillis();
	}

	public synchronized boolean tryAcquire() {
		long currentTime = System.currentTimeMillis();
		// 计算桶中漏水量
		long leakAmount = (currentTime - lastLeakTime) * rate / 1000;
		System.out.println("leakAmount " + leakAmount + " water " + water);
		water = Math.max(0, water - leakAmount);

		// 检查是否有足够的容量来处理请求
		if (water < capacity) {
			water++;
			lastLeakTime = currentTime;
			return true; // 允许请求
		} else {
			return false; // 桶已满，拒绝请求
		}
	}

	public static void main(String[] args) throws InterruptedException {
		LeakyBucketRateLimiter rateLimiter = new LeakyBucketRateLimiter(10, 5);
		Thread.sleep(2000);
		// 模拟请求
		for (int i = 0; i < 100; i++) {
			log.info("Allow Request: " + rateLimiter.tryAcquire());
			int i1 = new Random().nextInt(120);
			Thread.sleep(100); // 模拟请求间隔时间
		}
	}
}
